from classes.TestStep import TestStep
from classes.TestCase import TestCase
from classes.SCMAutoTestManager import SCMAutoTestManager
from classes.DataImporter import DataImporter
from classes.SCMBasicInfoMappingConfig import SCMBasicInfoMappingConfig
import os
import time

def process_sheet(manager, xls_path, col_mapping, sheet_name, required_field, all_fields, login_data, test_id, navigate_func, add_func):
    importer = DataImporter(xls_path, col_mapping, sheet_name=sheet_name)
    result = manager.test_login(input_data=login_data, test_id=test_id)
    if navigate_func:
        getattr(manager, navigate_func)(test_id=test_id)
    for test_data in importer.iter_test_data():
        # 检查必填字段为空则停止
        if not test_data.get(required_field) or str(test_data.get(required_field)).strip() == "":
            print(f"检测到{required_field}为空，停止导入。")
            return False  # 终止所有sheet处理
        # 动态补全所有字段
        for key in all_fields:
            if key not in test_data or test_data[key] is None:
                test_data[key] = ""
        print(test_data)
        add_result = getattr(manager, add_func)(input_data=test_data, test_id=test_id)
        # 检查add_func执行结果
        if add_result and "results" in add_result:
            for step_result in add_result["results"]:
                if step_result.get("status") == "failed":
                    print("执行失败，结果如下：")
                    print(add_result)
                    return True  # 失败则终止所有sheet处理
    return False  # 正常结束False

def run_test():
    api_url = "http://127.0.0.1:5000/api/test/execute"
    base_dir = os.path.dirname(os.path.abspath(__file__))
    element_json_path = os.path.join(base_dir, "resources", "elements.json")
    manager = SCMAutoTestManager(api_url=api_url, element_json_path=element_json_path)
    login_data = {
        "username": "admin",
        "password": "123456"
    }

    xls_path = "./custData/FrankTestData_BasicInfo.xlsx"
    batch_id = time.strftime("%Y%m%d_%H%M%S")
    for sheet_name, config in SCMBasicInfoMappingConfig.SHEET_CONFIG.items():
        test_id = f"{batch_id}"
        stop = process_sheet(
            manager,
            xls_path,
            config["col_mapping"],
            sheet_name,
            config["required_field"],
            config["fields"],
            login_data,
            test_id,
            config["navigate_func"],
            config["add_func"]
        )
        if stop:
            print(f"检测到 {sheet_name} 导入失败或必填字段为空，终止所有sheet处理。")
            break

if __name__ == "__main__":
    run_test()